#pragma strict
import System.Collections.Generic;
/////////////////////////////////////////////////////////////////////////////
//组合 蒙皮网格
/////////////////////////////////////////////////////////////////////////////
class CombineSkinnedMeshHelper{
	
	/////////////////////////////////////////////////////////////////////////////
	//组合tr下面的所有SkinnedMeshRenderer的mesh.destroySkin:是否删除当前的节点.
	//问题:
	//1 组合后,造成蒙皮不更新,动画不播放.
	/////////////////////////////////////////////////////////////////////////////
	static function CombineSkinnedMesh(tr:Transform,destroySkin:boolean){
		var smrs:SkinnedMeshRenderer[] = tr.GetComponentsInChildren.<SkinnedMeshRenderer>();
		
		var instances:List.<CombineInstance> = new List.<CombineInstance>();
		var mats:List.<Material> = new List.<Material>();
		var bones:List.<Transform> = new List.<Transform>();
		
		for(var smr:SkinnedMeshRenderer in smrs){
			//跳过 主tr
			if(smr.gameObject == tr.gameObject)
				continue;
			
			mats.AddRange(smr.materials);
			bones.AddRange(smr.bones);
			var mesh:Mesh = smr.sharedMesh;
			for(var i:int = 0;i<mesh.subMeshCount;i++){
				var instance:CombineInstance = CombineInstance();
					instance.mesh = mesh;
					instance.subMeshIndex = i;
				instances.Add(instance);
			}
			if(destroySkin)
				GameObject.Destroy(smr.gameObject);
		}
		
		var rootSmr:SkinnedMeshRenderer = tr.GetComponent.<SkinnedMeshRenderer>();
		if(! rootSmr){
			rootSmr = tr.gameObject.AddComponent.<SkinnedMeshRenderer>();
		}
		rootSmr.sharedMesh = Mesh();
		rootSmr.sharedMesh.CombineMeshes(instances.ToArray(),false,false);
		rootSmr.materials = mats.ToArray();
		rootSmr.bones = bones.ToArray();
	}
}